const service = require("../server/index");
const base64Img = require("base64-img");
const recognize = require("tesseractocr");
const gm = require("gm");
const path = require("path");

async function tesseract(newPath) {
  let text = await recognize(newPath);
  let code = text.replace(/\s/g, "");
  return code;
}

function disposeImg(imgPath, newPath, thresholdValue) {
  return new Promise((resolve, reject) => {
    gm(imgPath)
      .threshold(thresholdValue || "50%")
      .write(newPath, (err) => {
        if (err) return reject(err);
        resolve(newPath);
      });
  });
}

const getCode = async () => {
  let timestamp = new Date().getTime();
  let oldPath = path.join(__dirname, `../code/oldImage${timestamp}.png`);
  let newPath = path.join(__dirname, `../code/newImage${timestamp}.png`);
  let { data: res } = await service.get(
    "https://tongji-api.dcloud.net.cn/uni/stat/api/captcha"
  );
  let url = res.data.base64;
  let id = res.data.id;
  let codePath = "";

  base64Img.img(
    url,
    path.join(__dirname, "../code/"),
    `oldImage${timestamp}`,
    function (err, filepath) {
      codePath = filepath;
    }
  );

  await disposeImg(oldPath, newPath, "50%");
  let code = await tesseract(newPath);
  let data = {
    id,
    img: `http://localhost:3001/code/newImage${timestamp}.png`,
  };
  if (code) {
    data.code = code;
  }
  return data;
};

module.exports = getCode;
